<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input
            placeholder="请你输入搜索用户名"
            v-model="keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword" @click="searchUser">
            查询
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" size="default" @click="addUser">
        添加用户
      </el-button>
      <el-button type="primary" size="default" @click="batchDeleteSelected">
        批量删除
      </el-button>
      <el-table
        style="margin: 10px 0"
        border
        :data="userArr"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" />
        <el-table-column
          align="center"
          label="#"
          type="index"
        ></el-table-column>
        <el-table-column align="center" label="ID" prop="id"></el-table-column>
        <el-table-column
          align="center"
          label="用户名字"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户名称"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户角色"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`Are you sure to delete the ${row.username}?`"
              width="260px"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="false"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getUserInfoList"
      />
    </el-card>
    <!--  抽屉结构：完成添加与修改账号信息-->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请你输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请你输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请你输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">cancel</el-button>
          <el-button type="primary" @click="confirmClick">confirm</el-button>
        </div>
      </template>
    </el-drawer>
    <!--  分配角色-->
    <el-drawer v-model="drawer2">
      <template #header>
        <h4>分配角色(职位)</h4>
      </template>
      <template #default>
        <el-form :inline="true">
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              Check all
            </el-checkbox>
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(role, index) in allRole"
                :key="index"
                :value="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer2 = false">cancel</el-button>
          <el-button type="primary" @click="saveRole">confirm</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import {
  reqAddOrUpdateUser,
  reqAllRole,
  reqBatchDeleteUser,
  reqDeleteUser,
  reqSetUserRole,
  reqUserInfoList,
} from '@/api/acl/user'
import type {
  AllRole,
  AllRoleResponseData,
  Records,
  SetRoleData,
  User,
  UserResponseData,
} from '@/api/acl/user/type.ts'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting.ts'

let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
// 用户总个数
let total = ref<number>(0)
// 用户数组
let userArr = ref<Records>([])
// 获取全部已有的用户信息
const getUserInfoList = async (pager = 1) => {
  // 收集当前页码
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfoList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    userArr.value = result.data.records
    total.value = result.data.total
  }
}
onMounted(() => {
  getUserInfoList()
})
// @size-change 会传 每页大小size 用 一个函数隔离一下
// const handleSizeChange = (size: number) => {
const handleSizeChange = () => {
  // console.log(size)
  getUserInfoList()
}
let drawer = ref<boolean>(false)
// 添加用户按钮的回调
const addUser = () => {
  //显示抽屉
  drawer.value = true
  // 清空数据
  Object.assign(userParams.value, {
    id: 0, // id得清空，否则点击添加用户时，id没清空，会认为是更新用户
    username: '',
    name: '',
    password: '',
  })
  // 清除上一次的错误提示信息
  nextTick(() => {
    formRef.value.resetFields()
    //   formRef.value.clearValidate('username')  // 清空数据会导致 change 事件触发
    //   formRef.value.clearValidate('name')
    //   formRef.value.clearValidate('password')
  })
}
// 更新已有的用户信息的回调
const updateUser = (row: User) => {
  // 抽屉显示出来
  drawer.value = true
  //  将已有的用户信息赋值给userParams
  Object.assign(userParams.value, row)
  // 清除上一次的错误提示信息
  nextTick(() => {
    // formRef.value.resetFields()  // 不要用resetFileds，不然会清空表单，点击其他行数据回显永远是第一次打开的数据
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
// 收集用户信息用于上传的
let userParams = ref<User>({
  username: '',
  name: '',
  password: '',
})
const confirmClick = async () => {
  // 校验表单
  await formRef.value.validate()
  // 发请求
  let result: any = await reqAddOrUpdateUser(userParams.value)
  if (result.code == 200) {
    // 关闭抽屉
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.value.id ? '更新成功' : '添加成功',
    })
    // 刷新列表
    // await getUserInfoList(userParams.value.id ? pageNo.value : 1)
    // 浏览器自带刷新一次，解决修改了当前登陆账号被修改，不退出问题, 修改用户后刷新列表留在当前页码功能没用了
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: userParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
const cancelClick = () => {
  drawer.value = false
}
// 获取form组件实例
let formRef = ref<any>()
// 校验用户账号
const validatorUsername = (value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户姓名长度至少5位'))
  }
}
const validatorName = (value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称长度至少5位'))
  }
}
const validatorPassword = (value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码长度至少6位'))
  }
}
// 表单校验
const rules = {
  username: [
    { required: true, trigger: 'change', validator: validatorUsername },
  ],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

// 控制角色分配抽屉显示
let drawer2 = ref<boolean>(false)
/**
 * 点击分配角色按钮
 * @param row
 */
const setRole = async (row: User) => {
  // 收集当前用户的角色信息
  Object.assign(userParams.value, row)
  // 发请求获取所有角色
  let result: AllRoleResponseData = await reqAllRole(
    userParams.value.id as number,
  )
  if (result.code == 200) {
    // 存储全部职位数据
    allRole.value = result.data.allRolesList
    // 存储当前用户职位数据
    userRole.value = result.data.assignRoles
  }
  drawer2.value = true
}
const allRole = ref<AllRole>()
const userRole = ref<AllRole>()
// 全选复选框
const checkAll = ref<boolean>(false)
// 不确定样式
const isIndeterminate = ref<boolean>(true)
// 全选复选框改变
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 单选框改变
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value?.length // 可选
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value!.length //非空断言
}
const saveRole = async () => {
  // 收集参数
  let data: SetRoleData = {
    userId: userParams.value.id as number,
    roleIdList: userRole.value?.map((item) => item.id as number) as number[],
  }
  let result = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage.success('分配角色成功')
    drawer2.value = false
    await getUserInfoList(pageNo.value)
  }
}
/**
 * 删除用户
 * @param id
 */
const deleteUser = async (id: number) => {
  const result = await reqDeleteUser(id)
  if (result.code == 200) {
    ElMessage.success('删除成功')
    await getUserInfoList(
      userArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}
// 用于存储批量删除的用户的ID
let selectIdsArr = ref<User[]>([])
/**
 * table复选框触发
 * @param val 勾选的行 row
 */
const handleSelectionChange = (val: any) => {
  // 整理Id
  selectIdsArr.value = val
}
const batchDeleteSelected = async () => {
  let idsList: (number | undefined)[] = selectIdsArr.value.map(
    (item) => item.id,
  )
  const result: any = await reqBatchDeleteUser(idsList)
  if (result.code == 200) {
    ElMessage.success('批量删除成功')
    await getUserInfoList(
      userArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}
// 收集用户输入进来的搜索关键字
let keyword = ref<string>('')
const searchUser = () => {
  // 根据关键字搜索
  getUserInfoList()
  // 清空关键字
  keyword.value = ''
}
// 获取模板setting仓库
let settingStore = useLayOutSettingStore()
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
